using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Models.ServerModels;
using Newtonsoft.Json;

namespace DdnsServer.DnspodAPI
{
    public class APIBase
    {
        private Dictionary<string,object> commParam = null;
        private string userAgent = "";
        private string server = "";
        #region 构造函数
        public APIBase(ApiConfigModel cfg)
        {
            commParam = new Dictionary<string, object>
            {
                ["login_token"] = cfg.ApiId + "," + cfg.ApiToken,
                ["format"] = cfg.Format,
                ["lang"] = cfg.Lang,
                ["error_on_empty"] = cfg.ErrorOnEmpty,
                ["user_id"] = cfg.UserId
            };
            userAgent = string.IsNullOrEmpty(cfg.UserAgent)? "LNDDNS/v Unknow (lovesans@gmail.com)":cfg.UserAgent;
            server = cfg.ServerAddress;
        }
        #endregion
        #region 请求API
        protected T PostData<T>(string api, Dictionary<string,object> param =null)
        {
            //公共参数
            string pData = GetDataString(commParam);
            //其它参数
            if (param != null)
                pData += "&" + GetDataString(param);
            //HttpClient
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("User-Agent", userAgent);
                HttpContent content = new StringContent(pData, Encoding.UTF8, "application/x-www-form-urlencoded");
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3 | System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;
                var response = client.PostAsync(server + api, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    string retStr = response.Content.ReadAsStringAsync().Result;
                    return JsonConvert.DeserializeObject<T>(retStr);
                }
                else
                {
                    throw new Exception($"调用接口失败,StatusCode:{response.StatusCode.ToString()}");
                }
            }
        }
        #endregion
        #region 组合参数
        private string GetDataString(Dictionary<string,object> data)
        {
            if (null == data)
                return "";
            string retString = "";
            foreach (var item in data)
            {
                if (!string.IsNullOrEmpty(retString))
                    retString += "&";
                retString += item.Key + "=" + item.Value.ToString().Replace("=", "%3D");
            }
            return retString;
        }
        #endregion
    }
}
